const Base = require('./base.js');
const moment = require('moment');
const m = require('gm');
const { assign } = require('lodash');
const taskConfig = {
    graphic: 41,//41图文分享、42活动参与、43活动分享、44问卷参与、45问卷分享、46门店活动
    active1: 42,
    active2: 43,
    question1: 44,
    question2: 45,
    siteactive: 46,
    register: 21,//邀人注册
    share: 46//体验分享
};
//一次性的系统任务
const otask = [1, 2, 3];
module.exports = class extends Base {
    /**
     * 
     */
    /**
     * 小程序登录后获取激活的任务
     */
    async getOwnTaskAction() {
        const model = this.model('task');
        const integral_model = this.model('task_integral');
        const qo_model = this.model('question_user');
        const a_model = this.model('active_join');
        let seachdata = { id: ['>', 0], is_delete: 0 };
        const state = this.get('state') || '';
        const data = await model.where(seachdata).order('custom,id').select();
        for (const item of data) {//
            item.finish = 0;//标记是否完成状态
            item.progress = '';//完成进展
            if (otask.includes(item.source_type) && !think.isEmpty(await integral_model.where({ user_id: think.userId, task_id: item.id }).find())) {//如果是系统任务，且只允许做一次的任务,做过就是已完成的
                item.finish = 1;
            }
            //是否参与过问卷
            if (item.source_type == taskConfig.question1) {
                let qoption = await qo_model.where({ question_id: item.source_id, userid: think.userId }).find();
                if (!think.isEmpty(qoption)) item.finish = 1;
            }
            //是否参与过活动
            if (item.source_type == taskConfig.active1) {
                let a_u = await a_model.where({ active_id: item.source_id, user_id: think.userId, type: 'join' }).find();
                if (!think.isEmpty(a_u)) item.finish = 1;
            }
            //是否编写了体验
            if(item.source_type == 5){
                let todayTimeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
                const myshare = await this.model('share').where({addtime:['BETWEEN',todayTimeStamp,todayTimeStamp+86400],userid:think.userId}).find();
                if(!think.isEmpty(myshare)) item.finish = 1;
            }
            //完成度
            if (item.times) {
                let sum;
                switch (item.source_type) {
                    case 6:
                        sum = await this.model('share_click').where({ userid: think.userId ,is_finish:0}).count();
                        item.progress = sum % item.times + '/' + item.times;
                        break;
                    case 7:
                        sum = await this.model('systask_record').where({ task_id: item.id, invite_id: think.userId,is_finish:0 }).sum('times');
                        item.progress = sum % item.times + '/' + item.times;
                        break;
                    case 8:
                        sum = await this.model('systask_record').where({ task_id: item.id, invite_id: think.userId ,is_finish:0}).sum('times');
                        item.progress = sum % item.times + '/' + item.times;
                        break;
                    case 9:
                        sum = await this.model('systask_record').where({ task_id: item.id, invite_id: think.userId ,is_finish:0}).sum('times');
                        item.progress = sum % item.times + '/' + item.times;
                        break;
                    case taskConfig.graphic:
                        sum = await this.model('graphic_join').where({ graphic_id: item.source_id, shareuser_id: think.userId,is_finish:0 }).sum('times');
                        item.progress = sum % item.times + '/' + item.times;
                        break;
                    case taskConfig.active2:
                        sum = await this.model('active_join').where({ active_id: item.source_id, shareuser_id: think.userId,is_finish:0 }).count('distinct user_id');
                        item.progress = sum % item.times + '/' + item.times;
                        break;
                    case taskConfig.question2:
                        sum = await this.model('question_user').where({ question_id: item.source_id, invite_userid: think.userId,is_finish:0 }).count('distinct userid');
                        item.progress = sum % item.times + '/' + item.times;
                        break;
                    default:
                        item.progress = '';
                }
            } else {
                item.progress = '';
            }

        }
        return this.success(data);
    }

    async readAction() {
        const model = this.model('task');
        const id = this.get('id');
        const data = await model.where({ id: id }).find();
        return this.success(data);
    }


    async readDetailAction() {
        const model = this.model('task');
        const taskid = this.get('taskid');
        const model2 = this.model('active');
        const model1 = this.model('graphic');
        const model3 = this.model('question');
        const q_model3 = this.model('question_content');
        let data;
        let task = await model.where({ id: taskid }).find();
        switch (task.source_type) {
            case taskConfig.graphic:
                data = await model1.where({ id: task.source_id }).find();
                break;
            case taskConfig.active1:
                data = await model2.where({ id: task.source_id }).find();
                break;
            case taskConfig.active2:
                data = await model2.where({ id: task.source_id }).find();
                break;
            case taskConfig.question1:
                data = await model3.where({ id: task.source_id }).find();
                data.list = await q_model3.where({ question_id: task.source_id }).select();
                for (let i of data.list) {
                    i.option = JSON.parse(i.ques_option);
                }
                break;
            case taskConfig.question2:
                data = await model3.where({ id: task.source_id }).find();
                data.list = await q_model3.where({ question_id: task.source_id }).select();
                for (let i of data.list) {
                    i.option = JSON.parse(i.ques_option);
                }
                break;
            default:
                data = await model1.where({ id: task.source_id }).find();
        }

        return this.success({ task: task, detail: data });
    }
    /**
    * 
    */
    /**
     * 完成任务
     */
    async finishTaskAction() {
        const values = this.post();
        const id = this.post('taskid');
        const invite_id = this.post('invite_id');
        if (id < 1) {
            return this.fail(400, '请传入任务id');
        }
        const model = this.model('task');
        const s_model = this.model('systask_record');
        const integral_model = this.model('task_integral');
        const u_model = this.model('user');
        const task = await model.where({ id: id }).find();;
        if (think.isEmpty(task)) {
            return this.fail(400, '此任务不存在或已冻结');
        }
        if (task.is_delete > 0) {
            return this.fail(400, '此任务已冻结');
        }
        const now = moment().format('YYYY-MM-DD');
        if (now < task.begindate || now > task.enddate) {
            return this.fail(400, '活动期限已过');
        }
        const userid = think.userId;
        //如果是系统任务，只允许做一次
        if (task.custom == 0 && task.source_type != 21) {
            const integral_u = await integral_model.where({ user_id: userid, task_id: id }).find();
            if (!think.isEmpty(integral_u)) return this.fail(400, '你已完成该任务');
            let value = {
                task_id: id,
                task_type: task.task_type,
                user_id: userid,
                invite_id: invite_id ? invite_id : 0,
                integral: task.join_reward,
                is_finish: 1,
                reason: task.content
            };
            let u_id = await integral_model.add(value);
            return this.success(value);
        }
        switch (task.source_type) {
            case taskConfig.graphic:
                let value = {
                    task_id: id,
                    task_type: task.task_type,
                    user_id: userid,
                    invite_id: invite_id ? invite_id : 0,
                    integral: task.join_reward,
                    is_finish: 1,
                    reason: task.content
                };
                let u_id = await integral_model.add(value);
                return this.success(value);
            case taskConfig.active1:
                data = await model2.field("id,title").select();
                break;
            case taskConfig.active2:
                data = await model2.field("id,title").select();
                break;
            case taskConfig.question1:
                data = await model3.field("id,name as title").select();
                break;
            case taskConfig.question2:
                data = await model3.field("id,name as title").select();
                break;
            default:
                data = await model1.field("id,title").select();
        }
        return this.success(data);



    }

    async testTaskAction() {
        const values = this.post();
        const id = this.get('taskid');
        const invite_id = this.post('invite_id');
        if (id < 1) {
            return this.fail(400, '请传入任务id');
        }
        const model = this.model('task');
        const integral_model = this.model('task_integral');
        const task = await model.where({ id: id }).find();
        switch (task.source_type) {
            case 4:
                const integral_u = await integral_model.where({ user_id: think.userId, task_type: 1 }).find();
                if (!think.isEmpty(integral_u)) return this.fail(400, '你已绑定过手机');
                return this.success(1);
            default:
                return this.fail(400, '未知任务类型');
        }
    }

    /**
     * 完成系统任务
     */
    async finishSysTaskAction() {
        const values = this.post();
        const id = this.post('taskid');
        const invite_id = this.post('invite_id');
        if (id < 1) {
            return this.fail(400, '请传入任务id');
        }
        const model = this.model('task');
        const s_model = this.model('systask_record');
        const integral_model = this.model('task_integral');
        const u_model = this.model('user');
        const task = await model.where({ id: id }).find();
        if (think.isEmpty(task)) {
            return this.fail(400, '此任务不存在或已冻结');
        }
        if (task.is_delete > 0) {
            return this.fail(400, '此任务已冻结');
        }
        // const now = moment().format('YYYY-MM-DD');
        // if(now<task.begindate||now>task.enddate){
        //     return this.fail(400,'活动期限已过');
        // }
        const userid = think.userId;
        const user = await u_model.where({ id: userid }).find();
        //如果是前三个系统任务，只允许做一次
        if (otask.includes(task.source_type)) {
            const integral_u = await integral_model.where({ user_id: userid, task_id: id }).find();
            if (!think.isEmpty(integral_u)) return this.fail(400, '你已完成该任务');
            let value = {
                task_id: id,
                task_type: task.source_type,
                user_id: userid,
                invite_id: invite_id ? invite_id : 0,
                integral: task.join_reward,
                is_finish: 1,
                reason: task.content
            };
            let u_id = await integral_model.add(value);
            //修改本人获取积分
            await u_model.where({ id: userid }).increment('integral', value.integral);
            return this.success(value);
        }
        //其他邀请或分享的系统任务
        let dataid;
        if (task.custom != 0) return this.fail(400, '非系统任务');

        switch (task.source_type) {
            case 4:
                if (!invite_id) return this.fail(400, '邀请绑定,无邀请绑定人id')
                if (invite_id == userid) return this.sucess({ message: '点击自己的分享' });;
                const integral_u = await integral_model.where({ user_id: userid, task_type: 1 }).find();
                if (!think.isEmpty(integral_u)) return this.fail(400, '你已绑定过手机');
                const utask = await model.where({ source_type: 1, is_delete: 0 }).find();
                if (think.isEmpty(utask)) return this.fail(400, '绑定手机任务已冻结');
                //绑定手机得积分
                let u_id = await integral_model.add({
                    task_id: utask.id,
                    task_type: utask.source_type,
                    user_id: userid,
                    invite_id: invite_id ? invite_id : 0,
                    integral: utask.join_reward,
                    is_finish: 0,
                    reason: task.content
                });
                //修改本人获取积分
                // await u_model.where({id:userid}).update({integral:user.integral+utask.join_reward});
                await u_model.where({ id: userid }).increment('integral', utask.join_reward);
                //完成他人邀请记录
                let s_id = await s_model.add({
                    task_id: task.id,
                    task_type: task.source_type,
                    user_id: userid,
                    invite_id: invite_id ? invite_id : 0,
                    reason: '被邀请绑定手机号',
                    is_finish:1
                });
                //增加邀请人获得积分记录// 判断是否达到指定次数
                // const scount= await s_model.where({task_id:task_id}).count('id');
                // const icount= await integral_model.where({task_id:task_id}).count('id');
                // if(Math.floor(scount/1)>icount){
                dataid = await integral_model.add({
                    task_id: task.id,
                    task_type: task.source_type,
                    user_id: invite_id,
                    // invite_id:invite_id?invite_id:0,
                    integral: task.join_reward,
                    is_finish: 0,
                    reason: task.content
                });
                //修改邀请人的积分数据
                // const invite = await u_model.where({id:invite_id}).find();
                // await u_model.where({id:invite_id}).update({integral:invite.integral+task.join_reward});
                await u_model.where({ id: invite_id }).increment('integral', task.join_reward);
                // }

                return this.success(dataid);
            case 5:
                let todayTimeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
                const myshare = await this.model('share').where({addtime:['BETWEEN',todayTimeStamp,todayTimeStamp+86400],userid:userid}).find();
                if(!think.isEmpty(myshare)) return this.fail(400,'你今天已经编写过体验了');
                let sharedata=this.post('share')||'';
                if(!sharedata){
                    return this.fail(400,'体验内容不能为空');
                }
                //编写体验得积分
                await this.model('share').add({
                    title:sharedata.title,
                    content:sharedata.content,
                    userid:userid,
                    edit_reward:task.join_reward,
                    addtime:Math.floor(new Date().getTime() / 1000)
                });
                dataid = await integral_model.add({
                    task_id: task.id,
                    task_type: task.source_type,
                    user_id: userid,
                    // invite_id:invite_id?invite_id:0,
                    integral: task.join_reward,
                    is_finish: 0,
                    reason: task.content
                });
                //修改本人获取积分
                // await u_model.where({id:userid}).update({integral:user.integral+task.join_reward});
                await u_model.where({ id: userid }).increment('integral', task.join_reward);
                return this.success(dataid);
            case 6:
                if (!invite_id) return this.fail(400, '分享,无分享人id');
                let shareid=this.post('shareid')||0;
                if (!shareid) return this.fail(400, '缺少分享的体验id');
                const limit6 = task.click_times_limit ? task.click_times_limit : 10;
                const share=await this.model('share').where({id:shareid}).find();
                await this.model('share').where({id:shareid,is_share:0}).update({is_share:1});
                const usertimes= await this.model('share_click').where({ user_id: invite_id,click_userid: userid,share_id:shareid }).count();
                if (usertimes >= limit6) return this.success({ message: '点击次数上限' });
                let shareclick_id= await this.model('share_click').add({
                    click_userid: userid, 
                    userid: invite_id,
                    share_id:shareid,
                    share_title:share?share.title:''
                });
                const recordtimes= await this.model('share_click').where({ user_id: invite_id,finish:0 }).count();
                //增加邀请人获得积分记录// 判断是否达到指定次数
                if (task.times&&recordtimes>=task.times) {
                    dataid = await integral_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: invite_id,
                        // invite_id:invite_id?invite_id:0,
                        integral: task.times_reward,
                        is_finish: 0,
                        reason: task.content
                    });
                    //修改邀请人的积分数据
                    // const invite = await u_model.where({id:invite_id}).find();
                    await u_model.where({ id: invite_id }).increment('integral', task.times_reward);
                    //清空已统计数据
                    await this.model('share_click').where({ user_id: invite_id,finish:0 }).update({finish:1});

                }

                return this.success(dataid);
            case 7:
                //完成他人邀请记录
                if (!invite_id) return this.fail(400, '分享,无分享人id');
                //任务或单人任务获取积分上限
                let t_integral7 = await integral_model.where({ task_id: task.id }).sum('integral');
                if (task.max_reward && t_integral7 >= task.max_reward) {
                    return this.success({ message: '达到图文奖励上限，未获得积分' });
                }
                let u_integral7 = await integral_model.where({ task_id: task.id, user_id: invite_id }).sum('integral');
                if (task.everyone_max_reward && u_integral7 >= task.everyone_max_reward) {
                    return this.success({ message: '达到单人奖励上限，未获得积分' });
                }

                let limit7 = task.click_times_limit ? task.click_times_limit : 10;
                // const record7 = await s_model.where({ user_id: userid, task_id: task.id, invite_id: invite_id }).find();
                const usertims7= await s_model.where({ user_id: userid, task_id: task.id, invite_id: invite_id }).sum('times');
                if (usertims7 >= limit7) return this.success({ message: '点击次数上限' });
                    let s_id7 = await s_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: userid,
                        invite_id: invite_id ? invite_id : 0,
                        reason: '点击分享的图文'
                    });
                //增加邀请人获得积分记录// 判断是否达到指定次数
                const scount7 = await s_model.where({ task_id: id, invite_id: invite_id,is_finish:0 }).sum('times');
                // const icount7 = await integral_model.where({ task_id: id }).count('id');
                if (task.times&&scount7>=task.times) {
                    dataid = await integral_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: invite_id,
                        // invite_id:invite_id?invite_id:0,
                        integral: task.times_reward,
                        is_finish: 0,
                        reason: task.content
                    });
                    //修改邀请人的积分数据
                    // const invite = await u_model.where({id:invite_id}).find();
                    await u_model.where({ id: invite_id }).increment('integral', task.times_reward);
                    await s_model.where({ task_id: id, invite_id: invite_id,is_finish:0 }).update({is_finish:1});
                }

                return this.success(dataid);
            case 8:
                //完成他人邀请记录
                if (!invite_id) return this.fail(400, '分享,无分享人id');
                //任务或单人任务获取积分上限
                let t_integral = await integral_model.where({ task_id: task.id }).sum('integral');
                if (task.max_reward && t_integral >= task.max_reward) {
                    return this.success({ message: '达到图文奖励上限，未获得积分' });
                }
                let u_integral = await integral_model.where({ task_id: task.id, user_id: invite_id }).sum('integral');
                if (task.everyone_max_reward && u_integral >= task.everyone_max_reward) {
                    return this.success({ message: '达到单人奖励上限，未获得积分' });
                }

                let limit8 = task.click_times_limit ? task.click_times_limit : 10;
                const usertims8= await s_model.where({ user_id: userid, task_id: task.id, invite_id: invite_id }).sum('times');
                if (usertims8 >= limit8) return this.success({ message: '点击次数上限' });
                    let s_id8 = await s_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: userid,
                        invite_id: invite_id ? invite_id : 0,
                        reason: '点击商品推广'
                    });
                const scount8 = await s_model.where({ task_id: id, invite_id: invite_id,is_finish:0 }).sum('times');
                // const icount8 = await integral_model.where({ task_id: id }).count('id');
                if (task.times&&scount7>=task.times) {
                    dataid = await integral_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: invite_id,
                        // invite_id:invite_id?invite_id:0,
                        integral: task.times_reward,
                        is_finish: 0,
                        reason: task.content
                    });
                    //修改邀请人的积分数据
                    // const invite = await u_model.where({id:invite_id}).find();
                    await u_model.where({ id: invite_id }).increment('integral', task.times_reward);
                    await s_model.where({ task_id: id, invite_id: invite_id,is_finish:0 }).update({is_finish:1});
                }

                return this.success(dataid);
            case 9:
                if (!invite_id) return this.fail(400, '分享,无分享人id');
                //任务或单人任务获取积分上限
                let t_integral9 = await integral_model.where({ task_id: task.id }).sum('integral');
                if (task.max_reward && t_integral1 >= task.max_reward) {
                    return this.success({ message: '达到推广奖励上限，未获得积分' });
                }
                let u_integral9 = await integral_model.where({ task_id: task.id, user_id: invite_id }).sum('integral');
                if (task.everyone_max_reward && u_integral9 >= task.everyone_max_reward) {
                    return this.success({ message: '达到单人推广奖励上限，未获得积分' });
                }
                const limit9 = task.click_times_limit ? task.click_times_limit : 10;
                const record9 = await s_model.where({ user_id: userid, task_id: task.id, invite_id: invite_id }).find();
                if (think.isEmpty(record9)) {
                    //完成他人邀请记录
                    let s_id = await s_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: userid,
                        invite_id: invite_id ? invite_id : 0,
                        reason: '点击推广的小程序'
                    });
                } else {
                    return this.success({ message: '你已点击过' });
                    // if (record9.times >= limit9) return this.success({ message: '点击次数上限' });
                    // await s_model.where({ user_id: userid, task_id: task.id, invite_id: invite_id }).increment('times', 1);
                }
                //增加邀请人获得积分记录// 判断是否达到指定次数
                const scount9 = await s_model.where({ task_id: task.id,invite_id: invite_id,is_finish:0 }).count('times');
                // const icount9 = await integral_model.where({ task_id: task.id }).count('id');
                if (task.times&&scount7>=task.times) {
                    dataid = await integral_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: invite_id,
                        // invite_id:invite_id?invite_id:0,
                        integral: task.times_reward,
                        is_finish: 0,
                        reason: task.content
                    });
                    //修改邀请人的积分数据
                    // const invite = await u_model.where({id:invite_id}).find();
                    await u_model.where({ id: invite_id }).increment('integral', task.times_reward);
                    await s_model.where({ task_id: id, invite_id: invite_id,is_finish:0 }).update({is_finish:1});
                }

                return this.success(dataid);
            default:
                return this.fail(400, '未知任务类型');
        }

        // return this.success(data);

    }


    /**
     * 完成自定义任务  可能有很多改的
     */
    async finishOwnTaskAction() {
        const values = this.post();
        const id = this.post('taskid');
        const invite_id = this.post('invite_id');
        if (id < 1) {
            return this.fail(400, '请传入任务id');
        }
        const model2 = this.model('active_join');
        const model1 = this.model('graphic_join');
        const qjoin_model = this.model('question_user');
        const qo_model = this.model('question_option');

        const model = this.model('task');
        // const s_model = this.model('systask_record');
        const integral_model = this.model('task_integral');
        const u_model = this.model('user');
        const task = await model.where({ id: id }).find();
        if (think.isEmpty(task)) {
            return this.fail(400, '此任务不存在或已冻结');
        }
        if (task.is_delete > 0) {
            return this.fail(400, '此任务已冻结');
        }
        const now = moment().format('YYYY-MM-DD');
        if (now < task.begindate || now > task.enddate) {
            return this.fail(400, '活动期限已过');
        }
        const userid = think.userId;
        const user = await u_model.where({ id: userid }).find();
        let dataid;
        //TODO修改，任务可能有被修改的可能，所以这样写有逻辑错误
        switch (task.source_type) {
            case taskConfig.graphic:
                //点击分享的图文
                if (!invite_id) return this.fail(400, '分享,无分享人id');
                if (invite_id == userid) return this.success({ message: '点击自己的分享' });
                //任务或单人任务获取积分上限
                let t_integral1 = await integral_model.where({ task_id: task.id }).sum('integral');
                if (task.max_reward && t_integral1 >= task.max_reward) {
                    return this.success({ message: '达到图文奖励上限，未获得积分' });
                }
                let u_integral1 = await integral_model.where({ task_id: task.id, user_id: invite_id }).sum('integral');
                if (task.everyone_max_reward && u_integral1 >= task.everyone_max_reward) {
                    return this.success({ message: '达到单人奖励上限，未获得积分' });
                }

                let limit1 = task.click_times_limit ? task.click_times_limit : 10;
                // const record1 = await model1.where({ user_id: userid, shareuser_id: invite_id, graphic_id: task.source_id, type: 'join' }).find();
                const usertimes1 = await model1.where({ user_id: userid, shareuser_id: invite_id, graphic_id: task.source_id, type: 'join' }).sum('times');
                // if (think.isEmpty(record1)) {
                    //完成点击记录
                    let s_id1 = await model1.add({
                        graphic_id: task.source_id,
                        user_id: userid,
                        shareuser_id: invite_id ? invite_id : 0,
                        type: 'join'
                    });
                // } else {
                    if (usertimes1 >= limit1) return this.success({ message: '点击次数上限' });
                // }
                //增加邀请人获得积分记录// 判断是否达到指定次数
                const scount1 = await model1.where({ graphic_id: task.source_id, shareuser_id: invite_id,is_finish:0 }).sum('times');
                // const icount1 = await integral_model.where({ task_id: id }).count('id');
                if (task.times&&scount1>=task.times) {
                    dataid = await integral_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: invite_id,
                        // invite_id:invite_id?invite_id:0,
                        integral: task.times_reward,
                        is_finish: 0,
                        reason: task.content
                    });
                    //修改邀请人的积分数据
                    //    const invite = await u_model.where({id:invite_id}).find();
                    await u_model.where({ id: invite_id }).increment('integral', task.times_reward);
                    await model1.where({ graphic_id: task.source_id, shareuser_id: invite_id,is_finish:0 }).update({is_finish:1});
                }

                return this.success(dataid);
            case taskConfig.active1:
                const record2 = await model2.where({ user_id: userid, active_id: task.source_id, type: 'join' }).find();
                if (!think.isEmpty(record2)) return this.fail(400, '你已参与过该活动');
                let activeData = this.post('activeData');
                //添加参与记录
                let s_ida1 = await model2.add({
                    active_id: task.source_id,
                    user_id: userid,
                    //    shareuser_id:invite_id?invite_id:0,
                    type: 'join',
                    is_sign: this.post('is_sign') ? 1 : 0
                });
                let au_id = await this.model('active_user').add({
                    active_id: task.source_id,
                    user_id: userid,
                    name: activeData.name,
                    sex: activeData.sex,
                    phone: activeData.phone,
                    birth: activeData.birth,
                    is_sign: this.post('is_sign') ? 1 : 0
                });
                //参与奖励
                dataid = await integral_model.add({
                    task_id: task.id,
                    task_type: task.source_type,
                    user_id: userid,
                    // invite_id:invite_id?invite_id:0,
                    integral: this.post('is_sign') ? task.join_reward + task.sign_reward : task.join_reward,
                    is_finish: 0,
                    reason: this.post('is_sign') ? '参与并签到' : '参与'
                });
                //修改本人获取积分
                await u_model.where({ id: userid }).increment('integral', this.post('is_sign') ? task.join_reward + task.sign_reward : task.join_reward);
                return this.success(dataid);
            case taskConfig.active2:
                //点击分享的图文
                if (!invite_id) return this.fail(400, '分享,无分享人id');
                //任务或单人任务获取积分上限
                //    let t_integral = await integral_model.where({task_id:task.id}).sum('integral');
                //    if(task.max_reward&&t_integral>=task.max_reward){
                //        return this.success({message:'达到图文奖励上限，未获得积分'});
                //    }
                //    let u_integral = await integral_model.where({task_id:task.id,user_id:invite_id}).sum('integral');
                //    if(task.everyone_max_reward&&u_integral>=task.everyone_max_reward){
                //        return this.success({message:'达到单人奖励上限，未获得积分'});
                //    }

                //    let limit = task.click_times_limit?task.click_times_limit:10;


                const record3 = await model2.where({ user_id: userid, shareuser_id: invite_id, active_id: task.source_id, type: 'join' }).find();
                if (think.isEmpty(record3)) {
                    //完成点击记录
                    let s_id = await model2.add({
                        active_id: task.source_id,
                        user_id: userid,
                        shareuser_id: invite_id ? invite_id : 0,
                        type: 'join',
                        is_sign: this.post('is_sign') ? 1 : 0
                    });
                } else {
                    return this.fail(400, '你已参与过该活动');
                    //    await model1.where({user_id:userid,task_id:task.id,shareuser_id:invite_id,active_id:task.source_id,type:'join'}).increment('times',1);
                }
                //增加邀请人获得积分记录// 判断是否达到指定次数
                const scount3 = await model2.where({ active_id: task.source_id, shareuser_id: invite_id,is_finish:0 }).count('distinct user_id');
                // const icount3 = await integral_model.where({ task_id: id }).count('id');
                if (task.times&&scount3>=task.times) {
                    dataid = await integral_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: invite_id,
                        // invite_id:invite_id?invite_id:0,
                        integral: task.times_reward,
                        is_finish: 0,
                        reason: task.content
                    });
                    //修改邀请人的积分数据
                    //    const invite = await u_model.where({id:invite_id}).find();
                    await u_model.where({ id: invite_id }).increment('integral', task.times_reward);
                    await model2.where({ active_id: task.source_id, shareuser_id: invite_id,is_finish:0 }).update({is_finish:1});
                }

                return this.success(dataid);
            case taskConfig.question1:
                const record4 = await qjoin_model.where({ userid: userid, question_id: task.source_id }).find();
                if (!think.isEmpty(record4)) return this.fail(400, '你已参与过该问卷');
                let content = this.post('answerlist');
                let c_values = [];
                //添加问卷答案
                if (content) {
                    for (let i = 0; i < content.length; i++) {
                        let l = content[i];
                        for (let op of l.option) {
                            let c_v = {
                                question_id: task.source_id,
                                question_content_id: l.question_content_id,
                                option: op,
                                user_id: userid
                            }
                            c_values.push(c_v);
                        }

                    }
                }

                await qjoin_model.transaction(async () => {
                    let qjid = await qjoin_model.add({
                        question_id: task.source_id,
                        userid: userid
                    });
                    //那如果一个事务中涉及到多个model：
                    let c_model = this.model('question_option').db(qjoin_model.db());
                    await c_model.addMany(c_values);
                })
                //参与奖励
                dataid = await integral_model.add({
                    task_id: task.id,
                    task_type: task.source_type,
                    user_id: userid,
                    // invite_id:invite_id?invite_id:0,
                    integral: task.join_reward,
                    is_finish: 1,
                    reason: task.content
                });
                //修改本人获取积分
                await u_model.where({ id: userid }).increment('integral', task.join_reward);
                return this.success(dataid);
            case taskConfig.question2:
                //点击分享的图文
                if (!invite_id) return this.fail(400, '分享,无分享人id');
                //任务或单人任务获取积分上限
                // let t_integral = await integral_model.where({task_id:task.id}).sum('integral');
                // if(task.max_reward&&t_integral>=task.max_reward){
                //     return this.success({message:'达到图文奖励上限，未获得积分'});
                // }
                // let u_integral = await integral_model.where({task_id:task.id,user_id:invite_id}).sum('integral');
                // if(task.everyone_max_reward&&u_integral>=task.everyone_max_reward){
                //     return this.success({message:'达到单人奖励上限，未获得积分'});
                // }

                // let limit = task.click_times_limit?task.click_times_limit:10;

                const record5 = await qjoin_model.where({ userid: userid, question_id: task.source_id }).find();
                if (think.isEmpty(record5)) {
                    let content = this.post('answerlist');
                    let c_values = [];
                    //添加问卷答案
                    if (content) {
                        for (let i = 0; i < content.length; i++) {
                            let l = content[i];
                            for (let op of l.option) {
                                let c_v = {
                                    question_id: task.source_id,
                                    question_content_id: l.question_content_id,
                                    option: op,
                                    user_id: userid
                                }
                                c_values.push(c_v);
                            }

                        }
                    }

                    await qjoin_model.transaction(async () => {
                        let qjid = await qjoin_model.add({
                            question_id: task.source_id,
                            userid: userid,
                            shareuser_id: invite_id
                        });
                        //那如果一个事务中涉及到多个model：
                        let c_model = this.model('question_option').db(qjoin_model.db());
                        await c_model.addMany(c_values);
                    })
                } else {
                    return this.fail(400, '你已参与过该问卷');
                }
                //增加邀请人获得积分记录// 判断是否达到指定次数
                const scount5 = await qjoin_model.where({ question_id: task.source_id, invite_userid: invite_id,is_finish:0 }).count('distinct user_id');
                // const icount5 = await integral_model.where({ task_id: id }).count('id');
                if (task.times&&scount5>=task.times) {
                    dataid = await integral_model.add({
                        task_id: task.id,
                        task_type: task.source_type,
                        user_id: invite_id,
                        // invite_id:invite_id?invite_id:0,
                        integral: task.times_reward,
                        is_finish: 0,
                        reason: task.content
                    });
                    //修改邀请人的积分数据
                    // const invite = await u_model.where({id:invite_id}).find();
                    await u_model.where({ id: invite_id }).increment('integral', task.times_reward);
                    await qjoin_model.where({ question_id: task.source_id, invite_userid: invite_id,is_finish:0 }).update({is_finish:1});
                }

                return this.success(dataid);
            case taskConfig.siteactive:
                const siterecord = await this.model('active_site_user').where({ user_id: userid, active_site_id: task.source_id}).find();
                if (!think.isEmpty(siterecord)) return this.fail(400, '你已参与过该活动');
                let siteactiveData = this.post('siteactiveData');
                siteactiveData['user_id']=userid;
                siteactiveData['active_site_id']=task.source_id;
                //门店记录门店名及业务员TODO
                //添加参与记录
                let site_id = await this.model('active_site_user').add(siteactiveData);
                //参与奖励
                dataid = await integral_model.add({
                    task_id: task.id,
                    task_type: task.source_type,
                    user_id: userid,
                    // invite_id:invite_id?invite_id:0,
                    integral: task.join_reward,
                    is_finish: 1,
                    reason:'参与门店活动'
                });
                //修改本人获取积分
                await u_model.where({ id: userid }).increment('integral', this.post('is_sign') ? task.join_reward + task.sign_reward : task.join_reward);
                return this.success(dataid);
            default:
                return this.fail(400, '未知任务类型');
        }
        // return this.success(data);

    }


    async taskShareAction() {
        const id = this.post('taskid');
        if (id < 1) {
            return this.fail(400, '请传入任务id');
        }
        const model2 = this.model('active_join');
        const model1 = this.model('graphic_join');
        const model3 = this.model('question_share');
        const model = this.model('task');
        const task = await model.where({ id: id }).find();
        if (think.isEmpty(task)) {
            return this.fail(400, '此任务不存在或已冻结');
        }
        if (task.is_delete > 0) {
            return this.fail(400, '此任务已冻结');
        }
        const now = moment().format('YYYY-MM-DD');
        if (now < task.begindate || now > task.enddate) {
            return this.fail(400, '活动期限已过');
        }
        const userid = think.userId;
        let dataid;
        switch (task.source_type) {
            case taskConfig.graphic:
                const gs = await model1.where({ user_id: userid, graphic_id: task.source_id, type: 'share' }).find();
                if (think.isEmpty(gs)) {
                    dataid = await model1
                        .add({
                            user_id: userid,
                            graphic_id: task.source_id,
                            type: 'share'
                        });
                } else {
                    dataid = await model1.where({ user_id: userid, graphic_id: task.source_id, type: 'share' })
                        .increment('times', 1);
                }

                return this.success(dataid);
            case taskConfig.active2:
                const as = await model2.where({ user_id: userid, active_id: task.source_id, type: 'share' }).find();
                if (think.isEmpty(as)) {
                    dataid = await model2
                        .add({
                            user_id: userid,
                            active_id: task.source_id,
                            type: 'share'
                        });
                } else {
                    dataid = await model2.where({ user_id: userid, active_id: task.source_id, type: 'share' })
                    .increment('times', 1);
                }
                return this.success(dataid);
            case taskConfig.question2:
                const qs = await model3.where({ userid: userid, question_id: task.source_id }).find();
                if (think.isEmpty(qs)) {
                    dataid = await model3
                        .add({
                            userid: userid,
                            question_id: task.source_id,
                        });
                } else {
                    dataid = await model3.where({ userid: userid, question_id: task.source_id })
                        .update({
                            times: qs.times + 1
                        });
                }
                return this.success(dataid);
                case 6:
                    let shareid=this.post('shareid')||0;
                    const ss = await this.model('share_user').where({ userid: userid, share_id: shareid }).find();
                    if (think.isEmpty(ss)) {
                        dataid = await this.model('share_user')
                            .add({
                                userid: userid,
                                share_id: task.share_id,
                            });
                            await this.model('share').where({id:shareid}).update({is_share:1});
                    } else {
                        dataid = 0;
                    }
                    return this.success(dataid);
            default:
                return this.success(dataid);
        }

    }

    async getMyShareAction(){//获取我编写的体验
        const page = this.get('page')||1;
        const size = this.get('size')||6;
        const data = await this.model('share').where({
            userid:think.userId,
            is_verify:1,
            is_pass:1,
            is_delete:0
        }).order('id ASC').page(page,size).countSelect();
        return this.success(data);

    }
};